package com.sky.financelake.ui.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RadioGroup;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.DialogFragment;
import androidx.lifecycle.ViewModelProvider;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.sky.financelake.R;
import com.sky.financelake.base.BaseToolA;
import com.sky.financelake.bean.dto.RPlateZjlxDto;
import com.sky.financelake.common.Constants;
import com.sky.financelake.databinding.ActivityPlateZjlxRankBinding;
import com.sky.financelake.ui.dialog.PlateDialogF;
import com.sky.financelake.viewmodels.remote.ZjlxViewModel;

import java.util.ArrayList;
import java.util.List;

import dagger.hilt.android.AndroidEntryPoint;

/**
 * 资金流向
 */
@AndroidEntryPoint
public class PlateZjlxRankA extends BaseToolA {

    private ActivityPlateZjlxRankBinding binding;

    private BarChart barChart;
    private YAxis leftAxis;             //左侧Y轴
    private YAxis rightAxis;            //右侧Y轴
    private XAxis xAxis;                //X轴
    private Legend legend;              //图例
    private LimitLine limitLine;        //限制线
    private List<String> keys = new ArrayList<>();
    private ZjlxViewModel zjlxViewModel;
    private List<RPlateZjlxDto> simplePlateZjlxDtos = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityPlateZjlxRankBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        Toolbar toolbar = binding.toolbarContainer.toolbar;
        initToolbar(toolbar, getString(R.string.zjlx));

        zjlxViewModel = new ViewModelProvider(this).get(ZjlxViewModel.class);

        AppCompatTextView tvHy = binding.tvHy;
        tvHy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFragment dialogFragment = new PlateDialogF();
                Bundle bundle = new Bundle();
                bundle.putString("plate_name", Constants.PLATE_HY);
                dialogFragment.setArguments(bundle);
                dialogFragment.show(getSupportFragmentManager(), "HYF");
            }
        });

        AppCompatTextView tvGn = binding.tvGn;
        tvGn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFragment dialogFragment = new PlateDialogF();
                Bundle bundle = new Bundle();
                bundle.putString("plate_name", Constants.PLATE_GN);
                dialogFragment.setArguments(bundle);
                dialogFragment.show(getSupportFragmentManager(), "GNF");
            }
        });


        AppCompatTextView tvDy = binding.tvDy;
        tvDy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFragment dialogFragment = new PlateDialogF();
                Bundle bundle = new Bundle();
                bundle.putString("plate_name", Constants.PLATE_DY);
                dialogFragment.setArguments(bundle);
                dialogFragment.show(getSupportFragmentManager(), "DYF");
            }
        });

        RadioGroup rg = binding.rg;

        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_3:
                        zjlxViewModel.getPlateZjlxRank(3);
                        break;
                    case R.id.rb_5:
                        zjlxViewModel.getPlateZjlxRank(5);
                        break;
                    case R.id.rb_10:
                        zjlxViewModel.getPlateZjlxRank(10);
                        break;
                    case R.id.rb_20:
                        zjlxViewModel.getPlateZjlxRank(20);
                        break;
                }
            }
        });

        initBarChart();

        zjlxViewModel.getPlateZjlxRankLiveData().observe(this, response -> {
            simplePlateZjlxDtos.clear();
            List<RPlateZjlxDto> tmp = response.getResult();
            showBarChart(tmp, getString(R.string.plate_zjlx), getResources().getColor(R.color.design_default_color_error));

        });

        zjlxViewModel.getPlateZjlxRank(3);

    }


    /**
     * 初始化柱状图外观
     */
    private void initBarChart() {
        barChart = binding.barChart;
        /***图表设置***/
        //背景颜色
        barChart.setBackgroundColor(Color.WHITE);
        //不显示图表网格
        barChart.setDrawGridBackground(false);
        //背景阴影
        barChart.setDrawBarShadow(false);
        barChart.setHighlightFullBarEnabled(false);
        //显示边框
        barChart.setDrawBorders(false);
        //设置动画效果
        barChart.animateY(1000, Easing.Linear);
        barChart.animateX(1000, Easing.Linear);

        Description description = new Description();
        description.setEnabled(false);
        barChart.setDescription(description);


        /***XY轴的设置***/
        //X轴设置显示位置在底部
        xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setTextSize(6f);

        leftAxis = barChart.getAxisLeft();
        rightAxis = barChart.getAxisRight();
        //保证Y轴从0开始，不然会上移一点

        xAxis.setDrawAxisLine(false);
        leftAxis.setDrawAxisLine(false);
        rightAxis.setDrawAxisLine(false);
        rightAxis.setEnabled(false);


        leftAxis.setAxisMinimum(0f);
        leftAxis.setAxisMaximum(50f);

        ValueFormatter formatterY = new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
//                float v = value / 100000000f;
//                float v_ = (float) (Math.round(v * 100)) / 100;
//                Log.i(TAG, "getFormattedValue: " + value);
                return value + "亿";
            }
        };
        leftAxis.setValueFormatter(formatterY);

        //不显示X轴网格线
        xAxis.setDrawGridLines(false);
        xAxis.setLabelCount(10, false);
        //右侧Y轴网格线设置为虚线
        xAxis.enableGridDashedLine(10f, 10f, 0f);


        /***折线图例 标签 设置***/
        legend = barChart.getLegend();
        legend.setForm(Legend.LegendForm.LINE);
        legend.setTextSize(11f);
        //显示位置
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        //是否绘制在图表里面
        legend.setDrawInside(false);
    }


    /**
     * 柱状图始化设置 一个BarDataSet 代表一列柱状图
     *
     * @param barDataSet 柱状图
     * @param color      柱状图颜色
     */
    private void initBarDataSet(BarDataSet barDataSet, int color) {
        barDataSet.setColor(color);
        barDataSet.setFormLineWidth(1f);
        barDataSet.setFormSize(15.f);
        //不显示柱状图顶部值
        barDataSet.setDrawValues(true);
//        barDataSet.setValueTextSize(10f);
//        barDataSet.setValueTextColor(color);
    }


    public void showBarChart(List<RPlateZjlxDto> dateValueList, String name, int color) {
        ArrayList<BarEntry> entries = new ArrayList<>();
        ValueFormatter formatterX = new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                Log.i(TAG, "getFormattedValue: " + value);
                return dateValueList.get((int) value).getName();
            }
        };
        //X轴自定义值
        xAxis.setValueFormatter(formatterX);
        for (int i = 0; i < dateValueList.size(); i++) {
            float v = dateValueList.get(i).getZjlx() / 100000000f;
            float v_ = (float) (Math.round(v * 100)) / 100;
            /**
             * 此处还可传入Drawable对象 BarEntry(float x, float y, Drawable icon)
             * 即可设置柱状图顶部的 icon展示
             */

            BarEntry barEntry = new BarEntry(i, v_);
            entries.add(barEntry);
        }
        // 每一个BarDataSet代表一类柱状图
        BarDataSet barDataSet = new BarDataSet(entries, name);
        initBarDataSet(barDataSet, color);

//        // 添加多个BarDataSet时
//        ArrayList<IBarDataSet> dataSets = new ArrayList<>();
//        dataSets.add(barDataSet);
//        BarData data = new BarData(dataSets);

        BarData data = new BarData(barDataSet);
        data.setBarWidth(.5f);
        barChart.setData(data);
        barChart.setVisibleXRangeMaximum(10f);
        //更新
        barChart.notifyDataSetChanged();
        barChart.invalidate();
    }


}
